Multiple Catch Blocks In Java, a try block can be followed by multiple catch blocks. Each catch block must contain a different exception handler. Here’s an example:
Example of multiple catch block in exception handling using java
public class Main {
public static void main(String[] args) {
try {
int a[] = new int[5];
a[5] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output
Arithmetic Exception occurs
rest of the code
In this example, the try block contains two exceptions. But at a time only one exception occurs and its corresponding catch block is executed.
Nested Try-Catch Blocks In Java, using a try block inside another try block is permitted. It is called a nested try block. Here’s an example:
Example of Nested Try-Catch Blocks in exception handling using java
public class Main {
public static void main(String args[]) {
// outer try block
try {
// inner try block 1
try {
System.out.println("going to divide by 0");
int b = 39 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
// inner try block 2
try {
int a[] = new int[5];
// assigning the value out of array bounds
a[5] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("other statement");
}
// catch block of outer try block
catch (Exception e) {
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output
going to divide by 0
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
other statement
normal flow..
In this example, the inner try block is used to handle ArithmeticException while the outer try block is used to handle ArrayIndexOutOfBoundsException. If none of the catch block specified in the code is able to handle the exception, then the Java runtime system will handle the exception.